package com.pay.game.central.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.github.pagehelper.Page;
import com.pay.game.central.common.Result;
import com.pay.game.central.common.ResultGenerator;
import com.pay.game.central.security.annotaion.PassToken;
import com.pay.game.central.security.annotaion.UserLoginToken;
import com.pay.game.central.security.service.TokenService;
import com.pay.game.central.system.bean.Role;
import com.pay.game.central.system.bean.User;
import com.pay.game.central.system.service.UserService;
import com.pay.game.central.utils.RequestUtils;
import com.pay.game.central.utils.bean.MyHeader;
import com.pay.game.central.web.bean.InterestChangeRecord;
import com.pay.game.central.web.bean.Store;
import com.pay.game.central.web.service.HistoryOrderService;
import com.pay.game.central.web.service.InterestChangeRecordService;
import com.pay.game.central.web.service.SettlementService;
import com.pay.game.central.web.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    TokenService tokenService;
    @Autowired
    UserService userService;
    @Autowired
    StoreService storeService;
    @Autowired
    InterestChangeRecordService interestChangeRecordService;
    @Autowired
    SettlementService settlementService;
    @Autowired
    HistoryOrderService historyOrderService;


    /**
     * /user/login
     * POST
     * 登录
     * @requestBody {username:登录名,password:密码}
     * @return {token: token字符串}
     */
    @PassToken
    @PostMapping("/login")
    @ResponseBody
    Result<JSONObject> login(@RequestBody String json){
        JSONObject loginInfo = JSON.parseObject(json);
        String username = loginInfo.getString("username");
        String password = loginInfo.getString("password");
        JSONObject jsonObject = new JSONObject();
        User user = userService.getUserByNamePwd(username,password);
        if (user == null){
            return ResultGenerator.genFailResult("请输入正确的用户名和密码");
        }
        userService.userLogin(user.getId());
        String token = tokenService.getToken(user);
        jsonObject.put("token", token);
        return ResultGenerator.genSuccessResult(jsonObject);
    }

    /**
     *
     * @param json {token: ''}
     * @return {status: 0未过期,1已过期, token: 新的Token}
     */
    @PassToken
    @PostMapping("/token/check")
    @ResponseBody
    Result<JSONObject> checkToken(@RequestBody String json){
        JSONObject result = new JSONObject();
        result.put("status", 1);
        JSONObject loginInfo = JSON.parseObject(json);
        String token = loginInfo.getString("token");
        try {
            if(JWT.decode(token).getExpiresAt().getTime() > System.currentTimeMillis()){
                String userId = JWT.decode(token).getAudience().get(0);
                User user = userService.geValidateInfoById(userId);
                String newToken = tokenService.getToken(user);
                result.put("token", newToken);
                result.put("status", 0);
            }
        } catch (JWTDecodeException j) {
            // pass
        }
        return ResultGenerator.genSuccessResult(result);
    }

    @PassToken
    @GetMapping("/info")
    @ResponseBody
    Result<JSONObject> info(String token){
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            return ResultGenerator.genFailResult("错误的token");
        }
        return ResultGenerator.genSuccessResult(userService.getUserInfo(userId));
    }

    @PassToken
    @GetMapping("/detail")
    @ResponseBody
    Result<User> getUserDetail(String id){
        return ResultGenerator.genSuccessResult(userService.getUserDetail(id));
    }


    @PassToken
    @PostMapping("/logout")
    Result<String> logout(@RequestHeader Map<String, String> headers){
//        String token = headers.get("x-token");
//        String userId;
//        try {
//            userId = JWT.decode(token).getAudience().get(0);
//        } catch (JWTDecodeException j) {
//            return ResultGenerator.genFailResult("错误的token");
//        }
//        userService.userLogout(userId);
        return ResultGenerator.genSuccessResult("退出成功");
    }

    @UserLoginToken
    @PostMapping("/InterestRate")
    @ResponseBody
    Result<String> setInterestRate(@RequestBody String body,@RequestHeader Map<String, String> headers){
        MyHeader myHeader = RequestUtils.parseHeader(headers);
        JSONObject jsonObject = JSON.parseObject(body);
        String id = jsonObject.getString("id");
        float interestRate = jsonObject.getFloat("interestRate");
        userService.setInterestRate(interestRate,id);
        InterestChangeRecord interestChangeRecord = new InterestChangeRecord();
        interestChangeRecord.setOpt_user_id(myHeader.getUserId());
        interestChangeRecord.setUser_id(id);
        interestChangeRecord.setTime((int) (System.currentTimeMillis()/1000));
        interestChangeRecordService.addRecord(interestChangeRecord);
        return ResultGenerator.genSuccessResult("success");
    }

    @UserLoginToken
    @PostMapping
    @ResponseBody
    Result<String> addUser(@RequestBody String body) {
        JSONObject jsonObject = JSON.parseObject(body);
        String username = jsonObject.getString("username");
        //查询是否有相同登录名的用户
        User oldUser = userService.findUserByUserName(username);
        if (oldUser !=null ){
            return ResultGenerator.genSuccessResult("repeatName");
        }
        return  ResultGenerator.genSuccessResult(userService.addUser(jsonObject));
    }

    @UserLoginToken
    @DeleteMapping("/{id}")
    @ResponseBody
    Result<String> delete(@PathVariable String id){
        storeService.removeUserId(id);
        userService.deleteUserById(id);
        return ResultGenerator.genSuccessResult("success");
    }

    @UserLoginToken
    @PostMapping("/update")
    @ResponseBody
    Result<String> updateUserInfo(@RequestBody String body){
        User user = JSON.parseObject(body, User.class);
        userService.updateUserInfo(user);
        return ResultGenerator.genSuccessResult("success");
    }

    @UserLoginToken
    @PostMapping("/{id}/pause")
    @ResponseBody
    Result<String> updateUserPause(@PathVariable String id,@RequestBody String body){
        User user = JSON.parseObject(body, User.class);
        userService.updateUserPause(id, user.getPause());
        return ResultGenerator.genSuccessResult("success");
    }

    @UserLoginToken
    @PostMapping("/{id}/score")
    @ResponseBody
    Result<String> updateUserScore(@PathVariable String id,@RequestBody String body){
        User user = JSON.parseObject(body, User.class);
        userService.setScore(id, user.getScore());
        return ResultGenerator.genSuccessResult("success");
    }

    @UserLoginToken
    @GetMapping("/list")
    @ResponseBody
    Result<List<User>> list(@RequestHeader Map<String, String> headers,
                                String name,String username,String tel){
        MyHeader myHeader = RequestUtils.parseHeader(headers);
        return ResultGenerator.genSuccessResult(userService.list(username, name, tel, myHeader.getRootId()));
    }

    @UserLoginToken
    @GetMapping("/list/root")
    @ResponseBody
    Result<List<Map<String, Object>>> listRoot(){
        return ResultGenerator.genSuccessResult(userService.listRoot());
    }

    @UserLoginToken
    @GetMapping("/all")
    @ResponseBody
    Result<List<User>> all(@RequestHeader Map<String, String> headers){
        MyHeader myHeader = RequestUtils.parseHeader(headers);
        return ResultGenerator.genSuccessResult(userService.list("","", "",  myHeader.getRootId()));
    }

    @UserLoginToken
    @GetMapping("/{userId}/store")
    @ResponseBody
    public Result<Page<Store>> getUserStore(@PathVariable String userId){
        return ResultGenerator.genSuccessResult(storeService.getUserStore(userId));
    }

    @UserLoginToken
    @GetMapping("/{userId}/storeDetail")
    @ResponseBody
    public Result<Page<Map>> getUserStoreDetail(@PathVariable String userId){
        Page<Map> rlt = storeService.getUserStoreDetail(userId);
        Map<String ,Integer> notPaySize = historyOrderService.lockOrderSize();
        rlt.forEach(item -> {
            int size = notPaySize.getOrDefault(item.get("id").toString(),0);
            item.put("not_pay_size", size);
        });
        return ResultGenerator.genSuccessResult(rlt);
    }

    @UserLoginToken
    @GetMapping("/{userId}/roles")
    @ResponseBody
    public Result<List<Role>> listRole(@PathVariable String userId){
        return ResultGenerator.genSuccessResult(userService.listRole(userId));
    }

    @UserLoginToken
    @ResponseBody
    @PostMapping("/roles")
    public Result<String> setRoles(@RequestBody String body){
        JSONObject jsonObject = JSON.parseObject(body);
        String userId = jsonObject.getString("userId");
        List<Integer> roleIds = jsonObject.
                getJSONArray("roleIds")
                .stream()
                .map(item -> Integer.parseInt(item.toString()))
                .collect(Collectors.toList());
        userService.setRoles(userId,roleIds);
        return ResultGenerator.genSuccessResult("操作成功");
    }

    @UserLoginToken
    @DeleteMapping("/{userId}/role/{roleId}")
    @ResponseBody
    Result<String> remove(@PathVariable String userId, @PathVariable String roleId){
        userService.removeRole(userId, roleId);
        return ResultGenerator.genSuccessResult("操作成功");
    }

    @UserLoginToken
    @PostMapping("/{id}/store/start")
    @ResponseBody
    Result<String> startAllStore(@PathVariable String id){
        storeService.startByUserId(id);
        return ResultGenerator.genSuccessResult("操作成功");
    }

    @UserLoginToken
    @PostMapping("/{id}/store/stop")
    @ResponseBody
    Result<String> stopAllStore(@PathVariable String id){
        storeService.stopByUserId(id);
        return ResultGenerator.genSuccessResult("操作成功");
    }

    /**
     * 获取用户统计信息
     */
    @UserLoginToken
    @GetMapping("/{id}/countInfo")
    @ResponseBody
    Result<Map<String, Object>> countInfo(@PathVariable String id, String startDate, String endDate, String today){
        return ResultGenerator.genSuccessResult(settlementService.countInfo(id, startDate, endDate, today));
    }

    @UserLoginToken
    @GetMapping("/{id}/manageInfo")
    @ResponseBody
    Result<List<Map>> manageInfo(@PathVariable String id , @RequestHeader Map<String, String> headers){
        MyHeader myHeader = RequestUtils.parseHeader(headers);
        if (myHeader.isAdmin()){
            return ResultGenerator.genSuccessResult(userService.getManageInfo(null));
        }
        else return ResultGenerator.genSuccessResult(userService.getManageInfo(id));
    }

    @UserLoginToken
    @PostMapping("/{id}/manageInfo")
    @ResponseBody
    Result<Boolean> editManageInfo(@PathVariable String id, @RequestBody String body){
        JSONObject jsonObject = JSON.parseObject(body);
        int score = jsonObject.getIntValue("score");
        float interest_rate = jsonObject.getFloatValue("interest_rate");
        int order_limit = jsonObject.getIntValue("order_limit");
        userService.editManageInfo(id, score, interest_rate, order_limit);
        return ResultGenerator.genSuccessResult(true);
    }
}
